<?php
class ModelReportCoupon extends Model {
	public function getCoupons($filter = null) {
		$sql = "SELECT ch.coupon_id, c.name, c.code, COUNT(DISTINCT ch.order_id) AS `orders`, SUM(ch.amount) AS total
				FROM `@@coupon_history` ch LEFT JOIN `@@coupon` c ON (ch.coupon_id = c.coupon_id)";

		$implode = array();

		if ($filter) {
			if ($filter->get('filter_date_start')) {
				$implode[] = "DATE(c.date_added) >= '" . ES($filter->get('filter_date_start')) . "'";
			}
	
			if ($filter->get('filter_date_end')) {
				$implode[] = "DATE(c.date_added) <= '" . ES($filter->get('filter_date_end')) . "'";
			}
		}
		
		if ($implode) {
			$sql .= " WHERE " . implode(" AND ", $implode);
		}

		$sql .= " GROUP BY ch.coupon_id ORDER BY total DESC";

		if ($filter) {
			$sql .= $filter->limit();
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}

	public function getTotalCoupons($filter = null) {
		$sql = "SELECT COUNT(DISTINCT coupon_id) AS total FROM `@@coupon_history`";

		$implode = array();

		if ($filter) {
			if ($filter->get('filter_date_start')) {
				$implode[] = "DATE(date_added) >= '" . ES($filter->get('filter_date_start')) . "'";
			}
	
			if ($filter->get('filter_date_end')) {
				$implode[] = "DATE(date_added) <= '" . ES($filter->get('filter_date_end')) . "'";
			}
		}

		if ($implode) {
			$sql .= " WHERE " . implode(" AND ", $implode);
		}

		return $this->db->queryOne($sql);
	}
}
?>